package com.easyclearance.baseutil;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
 
public class TaskScheduler {
 
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private final AtomicBoolean taskRunning = new AtomicBoolean(false);
 
    public void startTask(Runnable task, long initialDelay, long period) {
        scheduler.scheduleAtFixedRate(() -> {
            taskRunning.set(true);
            try {
                task.run();
            } finally {
                taskRunning.set(false);
            }
        }, initialDelay, period, TimeUnit.SECONDS);
    }
 
    public boolean isTaskRunning() {
        return taskRunning.get();
    }
 
    public static void main(String[] args) {
        TaskScheduler scheduler = new TaskScheduler();
        Runnable task = () -> {
            // Task logic here
            System.out.println("Task is running...");
            try {
                Thread.sleep(2000); // Simulate task execution
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        };
 
        scheduler.startTask(task, 0, 3);
 
        while (true) {
            if (scheduler.isTaskRunning()) {
                System.out.println("Task is still running...");
            } else {
                System.out.println("Task has finished executing.");
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }
    }
}
